#include "class_tcp.h"


static uint16_t tcp_port = 10113;
class_client::class_client()
{
    client_fd = -1;
    client_port = 0;
    for (int var = 0; var < INET_ADDRSTRLEN; ++var) {
        client_ip[var] = '\0';
    }
}

class_TCP::class_TCP()
{
    run = 1;
    vec_clients.resize(30);
    class_client* cptr = nullptr;
    for (int i_vector = 0; i_vector < 30; ++i_vector) {
        cptr = new class_client();
        vec_clients[i_vector] = cptr;
        cout<<"vec_clients["<<i_vector<<"].client_port:"<<vec_clients[i_vector]->client_port<<endl;
    }
}

int class_TCP::initTCPserver()
{
    // 创建服务器套接字
    server_fd_ = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
    if (server_fd_ == -1) {
        std::cerr << "创建套接字失败: " << strerror(errno) << std::endl;
        return 0;
    }

    // 设置套接字选项，允许地址重用
    int opt = 1;
    if (setsockopt(server_fd_, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1) {
        std::cerr << "设置套接字选项失败: " << strerror(errno) << std::endl;
        close(server_fd_);
        return 0;
    }

    // 绑定地址
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(tcp_port);

    if (bind(server_fd_, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
        std::cerr << "绑定地址失败: " << strerror(errno) << std::endl;
        close(server_fd_);
        return 0;
    }

    // 开始监听
    if (listen(server_fd_, SOMAXCONN) == -1) {
        std::cerr << "监听失败: " << strerror(errno) << std::endl;
        close(server_fd_);
        return 0;
    }

    // 创建 epoll 实例
    epoll_fd_ = epoll_create1(0);
    if (epoll_fd_ == -1) {
        std::cerr << "创建 epoll 实例失败: " << strerror(errno) << std::endl;
        close(server_fd_);
        return 0;
    }
    // 添加服务器套接字到 epoll
    struct epoll_event ev;
    ev.events = EPOLLIN;
    ev.data.fd = server_fd_;
    if (epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, server_fd_, &ev) == -1) {
        std::cerr << "添加服务器套接字到 epoll 失败: " << strerror(errno) << std::endl;
        close(server_fd_);
        close(epoll_fd_);
        return 0;
    }

    std::cout << "服务器启动成功，监听端口: " << tcp_port << std::endl;
    return 1;
}

void class_TCP::runTCPserver()
{
    const int MAX_EVENTS = 64;
    struct epoll_event events[MAX_EVENTS];

    while (run > 0) {
        int nfds = epoll_wait(epoll_fd_, events, MAX_EVENTS, 5);
        if (nfds == -1) {
            if (errno == EINTR) {
                continue; // 被信号中断，继续等待
            }
            std::cerr << "epoll_wait 失败: " << strerror(errno) << std::endl;
            break;
        }

        for (int i = 0; i < nfds; ++i) {
            if (events[i].data.fd == server_fd_) {
                // 新的客户端连接
                handleNewConnection();
            } else {
                // 客户端数据可读或连接关闭
                handleClientEvent(events[i].data.fd, events[i].events);
            }
        }
    }
}

void class_TCP::handleNewConnection() {
    struct sockaddr_in client_addr;
    socklen_t client_len = sizeof(client_addr);

    int client_fd = accept(server_fd_, (struct sockaddr*)&client_addr, &client_len);
    if (client_fd == -1) {
        std::cerr << "接受连接失败: " << strerror(errno) << std::endl;
        return;
    }

    // 设置客户端套接字为非阻塞模式
    int flags = fcntl(client_fd, F_GETFL, 0);
    fcntl(client_fd, F_SETFL, flags | O_NONBLOCK);

    // 获取客户端IP和端口
    char client_ip[INET_ADDRSTRLEN];
    inet_ntop(AF_INET, &client_addr.sin_addr, client_ip, INET_ADDRSTRLEN);
    uint16_t client_port = ntohs(client_addr.sin_port);

    int serchresult = -1;
    for (int i_vector = 0; i_vector < 30; ++i_vector) {
        if(vec_clients[i_vector]->client_port == 0)
        {
            serchresult = i_vector;
            vec_clients[i_vector]->client_port = client_port;
            vec_clients[i_vector]->client_fd = client_fd;
            for (int var = 0; var < INET_ADDRSTRLEN; ++var) {
                vec_clients[i_vector]->client_ip[var] = client_ip[var];
            }
            break;
        }
        else
        {
            cout<< "vec_clients["<<i_vector<<"]->client_port=" << vec_clients[i_vector]->client_port<<endl;
        }
    }

    if(serchresult > -1)
    {
        // 添加客户端套接字到 epoll
        struct epoll_event ev;
        ev.events = EPOLLIN | EPOLLET; // 边缘触发模式
        ev.data.fd = client_fd;
        if (epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, client_fd, &ev) == -1) {
            cout<< "添加客户端套接字到 epoll 失败: " << strerror(errno)<<endl;
            vec_clients[serchresult]->client_fd = -1;
            vec_clients[serchresult]->client_port = 0;
        }
        else
        {
            string str_ip(vec_clients[serchresult]->client_ip);
            cout<< "new client IP: " << str_ip<<endl;
            cout<< "new client Port: " << vec_clients[serchresult]->client_port<<endl;
            for (int i_vector = 0; i_vector < 30; ++i_vector) {
                 cout<< "vec_clients["<<i_vector<<"]->client_port=" << vec_clients[i_vector]->client_port<<endl;
            }
        }
    }
    else
    {
        std::cerr << "客户端 超出最大连接数限制" << std::endl;
        close(client_fd);
        return;
    }
}

void class_TCP::handleClientEvent(int fd, uint32_t events)
{
    for (int i_vector = 0; i_vector < 30; ++i_vector) {
        if(vec_clients[i_vector]->client_fd == fd)
        {
            if (events & EPOLLIN) {
                // 客户端数据可读
                char buffer[4096];
                ssize_t bytes_read;

                while ((bytes_read = read(fd, buffer, sizeof(buffer))) > 0) {
                    handleData(buffer, bytes_read,i_vector);
                    if (write(fd, buffer, bytes_read) < 0) {
                        std::cerr << "发送数据失败: " << strerror(errno) << std::endl;
                        break;
                    }
                }

                if (bytes_read == 0 || (bytes_read == -1 && errno != EAGAIN && errno != EWOULDBLOCK)) {
                    // 连接关闭或读错误
                    close(vec_clients[i_vector]->client_fd);
                    vec_clients[i_vector]->client_port = 0;
                    vec_clients[i_vector]->client_fd = -1;
                }
            } else if (events & (EPOLLERR | EPOLLHUP)) {
                // 错误或挂起
                vec_clients[i_vector]->client_port = 0;
                vec_clients[i_vector]->client_fd = -1;
            }
        }
    }
}

void class_TCP::handleData(char *data, ssize_t bytes_read,int i_d)
{
    string str_ip(vec_clients[i_d]->client_ip);
    cout<<"get mes from: "<<str_ip<<endl;
    cout<<"bytes_read: "<<bytes_read<<endl;
    cout<<"read data : "<<data<<endl;

}

void class_TCP::sendTW(float ft, float fw)
{
    // std::cout << "当前 温度 值为: " << ft << std::endl;
    // std::cout << "当前 湿度 值为: " << fw << std::endl;
}



















